package com.zzyl.framework.interceptor;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @Description MemberInterceptor
 * @Author qiyuan
 * @Date 2025-07-23
 */
@Slf4j
@Component
public class MemberInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

         HandlerInterceptor.super.preHandle(request, response, handler);

         //1.拦截控制器的请求，如果不是控制器的请求则放行
        if (!(handler instanceof HandlerMethod)){
            return true;
        }

         //2.获取请求头的authorization如果没有则返回401
        String token = request.getHeader("authorization");

        if(StrUtil.isEmpty( token)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new BaseException("认证失败");
        }

        //3.解析 token，获取载荷，若为空则返回401
        Claims claims = tokenService.parseToken(token);
        if(ObjectUtil.isEmpty( claims)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new BaseException("认证失败");
        }

        //4.获取载荷中的userId，若为空则返回401
        Object userIdOBJ = claims.get("userId");

        if(ObjectUtil.isEmpty( userIdOBJ)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new BaseException("认证失败");
        }

        Long userId = Long.parseLong(userIdOBJ.toString());
        //5.将有效的userId保存到ThreadLocal中
        UserThreadLocal.set(userId);

         //放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空ThreadLocal
        UserThreadLocal.remove();
    }
}
